<?php
// +----------------------------------------------------------------------
// | XShop小程序商城
// +----------------------------------------------------------------------
// | Author: Peak Xin <xinyflove@gmail.com>
// +----------------------------------------------------------------------

namespace app\api\controller\v1;

use app\api\model\User as UserModel;
use app\api\model\UserAddress as UserAddressModel;
use app\api\service\Token as TokenService;
use app\api\validate\AddressNew;
use app\lib\exception\SuccessMessage;
use app\lib\exception\UserException;
use think\Controller;

class Address extends BaseController {

    protected $beforeActionList = array(
        '_checkPrimaryScope' => ['only' => 'getUserAddress,createOrUpdateAddress']
    );

    /**
     * 获取用户地址
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws UserException
     */
    public function getUserAddress()
    {
        $uid = TokenService::getCurrentUid();
        $userAddress = UserAddressModel::where('user_id', $uid)->find();
        if(!$userAddress)
        {
            throw new UserException([
                'msg' => '用户地址不存在',
                'errorCode' => 60001
            ]);
        }
        return $userAddress;
    }

    /**
     * 创建或更新地址
     * @return \think\response\Json
     * @throws UserException
     * @throws \app\lib\exception\ParameterException
     */
    public function createOrUpdateAddress()
    {
        $validate = new AddressNew();
        $validate->goCheck();
        // 根据Token来获取uid
        $uid = TokenService::getCurrentUid();
        // 根据uid查找用户数据,判断用户是否存在，如果不存在抛出异常
        $user = UserModel::get($uid);
        if(!$user) throw new UserException();
        // 获取用户从客户端提交的的地址信息
        $dataArray = $validate->getDataByRule(input('post.'));
        // 根据用户地址信息是否存在，从而判断是否添加地址还是更新地址
        $userAddress = $user->address;
        if(!$userAddress)
        {
            // 新增(利用模型关联保存)
            $user->address()->save($dataArray);
        }
        else
        {
            // 更新(利用模型关联保存)
            $user->address->save($dataArray);
        }

        //return $user;
        return json(new SuccessMessage(), 201);
    }
}